package org.apache.ibatis.demo.handler;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Optional;

/**
 * 自定义的金额类型
 *
 * @author zhaohui
 */
public class MyAmount implements Serializable {

    private BigDecimal amount;

    public MyAmount(BigDecimal amount) {
        this.amount = Optional.ofNullable(amount).orElse(BigDecimal.ZERO).setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    public BigDecimal bigDecimalValue() {
        return Optional.ofNullable(this.amount).orElse(BigDecimal.ZERO).setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    public void add(MyAmount anotherAmount) {
        this.amount = null != this.amount && null != anotherAmount ? this.amount.add(anotherAmount.amount) : this.amount;
        this.amount = Optional.ofNullable(this.amount).orElse(BigDecimal.ZERO).setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    public void sub(MyAmount anotherAmount) {
        this.amount = null != this.amount && null != anotherAmount ? this.amount.subtract(anotherAmount.amount) : this.amount;
        this.amount = Optional.ofNullable(this.amount).orElse(BigDecimal.ZERO).setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    public void mul(MyAmount anotherAmount) {
        this.amount = null != this.amount && null != anotherAmount ? this.amount.multiply(anotherAmount.amount) : this.amount;
        this.amount = Optional.ofNullable(this.amount).orElse(BigDecimal.ZERO).setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    public void div(MyAmount anotherAmount) {
        this.amount = null != this.amount && null != anotherAmount ? this.amount.divide(anotherAmount.amount) : this.amount;
        this.amount = Optional.ofNullable(this.amount).orElse(BigDecimal.ZERO).setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    @Override
    public String toString() {
        return null != this.amount ? this.amount.toString() : null;
    }

}
